package cn.hyh.core.component;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @auther :hyh
 * @desc :           包装的request。。。。。
 * @date :2019/7/29
 */
public class RequestWrapper  extends HttpServletRequestWrapper {

    private final String body;


    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        int contentLength = request.getContentLength();
        byte[] buffer = new byte[contentLength];
        ServletInputStream inputStream = request.getInputStream();
        inputStream.read(buffer);
        this.body = new String(buffer,0,contentLength,"iso-8859-1");
        inputStream.close();
    }

    public String getBody() {
        return body;
    }



    @Override
    public ServletInputStream getInputStream()  {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read(){
                return bais.read();
            }
        };
    }

    @Override
    public BufferedReader getReader(){
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

}
